.section .text.boot, "ax"
.global __start
__start:
    mrs x1, CurrentEl

    cmp x1,0xC
    beq secure_monitor_init

    cmp x1, 0x8
    beq hypervisor_init

    ldr x1, =__stack_base
    mov sp, x1

    b kernelMain

secure_monitor_init:
    b secure_monitor_init

hypervisor_init:
    b hypervisor_init


// 异常处理
.macro ventry label
.align 7
    b \label\()
.endm

.macro ventry_jump label
\label\():
    save_x0_x30_registers
    bl \label\()_handler
    restore_x0_x30_registers
    eret
.endm

.macro save_x0_x30_registers
    sub sp, sp, 0xFF
    stp x0, x1, [sp, #16 * 0]
    stp x2, x3, [sp, #16 * 1]
    stp x4, x5, [sp, #16 * 2]
    stp x6, x7, [sp, #16 * 3]
    stp x8, x9, [sp, #16 * 4]
    stp x10, x11, [sp, #16 * 5]
    stp x12, x13, [sp, #16 * 6]
    stp x14, x15, [sp, #16 * 7]
    stp x16, x17, [sp, #16 * 8]
    stp x18, x19, [sp, #16 * 9]
    stp x20, x21, [sp, #16 * 10]
    stp x22, x23, [sp, #16 * 11]
    stp x24, x25, [sp, #16 * 12]
    stp x26, x27, [sp, #16 * 13]
    stp x28, x29, [sp, #16 * 14]
    str x30,  [sp, #16 * 15]
.endm

.macro restore_x0_x30_registers
    ldp x0, x1, [sp, #16 * 0]
    ldp x2, x3, [sp, #16 * 1]
    ldp x4, x5, [sp, #16 * 2]
    ldp x6, x7, [sp, #16 * 3]
    ldp x8, x9, [sp, #16 * 4]
    ldp x10, x11, [sp, #16 * 5]
    ldp x12, x13, [sp, #16 * 6]
    ldp x14, x15, [sp, #16 * 7]
    ldp x16, x17, [sp, #16 * 8]
    ldp x18, x19, [sp, #16 * 9]
    ldp x20, x21, [sp, #16 * 10]
    ldp x22, x23, [sp, #16 * 11]
    ldp x24, x25, [sp, #16 * 12]
    ldp x26, x27, [sp, #16 * 13]
    ldp x28, x29, [sp, #16 * 14]
    ldr x30,  [sp, #16 * 15]
    add sp, sp, 0xFF
.endm

.section .text.exceptions_el1
.align 11
.global exceptions_el1
exceptions_el1:
    ventry current_el_sp0_sync
    ventry current_el_sp0_irq
    ventry current_el_sp0_fiq
    ventry current_el_sp0_serror

    ventry current_el_spx_sync
    ventry current_el_spx_irq
    ventry current_el_spx_fiq
    ventry current_el_spx_serror

    ventry current_el_aarch64_sync
    ventry current_el_aarch64_irq
    ventry current_el_aarch64_fiq
    ventry current_el_aarch64_serror

    ventry current_el_aarch32_sync
    ventry current_el_aarch32_irq
    ventry current_el_aarch32_fiq
    ventry current_el_aarch32_serror 

ventry_jump current_el_sp0_sync
ventry_jump current_el_sp0_irq
ventry_jump current_el_sp0_fiq
ventry_jump current_el_sp0_serror

ventry_jump current_el_spx_sync
ventry_jump current_el_spx_irq
ventry_jump current_el_spx_fiq
ventry_jump current_el_spx_serror

ventry_jump current_el_aarch64_sync
ventry_jump current_el_aarch64_irq
ventry_jump current_el_aarch64_fiq
ventry_jump current_el_aarch64_serror

ventry_jump current_el_aarch32_sync
ventry_jump current_el_aarch32_irq
ventry_jump current_el_aarch32_fiq
ventry_jump current_el_aarch32_serror

